﻿/// <reference path="CamlBuilder.js" />
ExecuteOrDelayUntilScriptLoaded(CheckAndRun, "sp.js");
var returnedTasks = new Array();
var returnedHistoryItems = new Array();
var currentItemId = null;
var matchingWorkflowTasksCount = 0;
var matchingHistoryItemsCount = 0;
var resultImageUrl = null;
var currentlistGuid = null;
var list = null;

function CheckAndRun() {
    var pathname = window.location.pathname;
    currentItemId = GetQueryStringVal('ID');
    if (currentItemId != null && pathname.indexOf("_layouts") == -1) {
        DoInlineWorkflowTasks();
    }
}

function DoInlineWorkflowTasks() {
    $("#relatedTasks").remove();
    $("#relatedHistoryItems").remove();
    returnedTasks.length = 0;
    returnedHistoryItems.length = 0;
    PopulateWorkflowTasksUsingListGuidAndItemId();
    PopulateWorkflowHistoryItems();
}




function PopulateWorkflowTasksUsingListGuidAndItemId() {
    var ctx = new SP.ClientContext.get_current();
    list = ctx.get_web().get_lists().getByTitle($(".die").find("a").text());
    ctx.load(list);
    ctx.executeQueryAsync(GetRelatedTasksForCurrentItem, null);
}





function GetRelatedTasksForCurrentItem(sender, args) {
    var queryText = "";
    currentlistGuid = list.get_id();
    var caml = new CamlBuilder();
    caml = caml.Where();
    var query = caml.NoteField('WorkflowListId').EqualTo(currentlistGuid).And().NumberField('WorkflowItemId').EqualTo(currentItemId).ToString().slice(7, -8);
    queryText = joinQueryElements(queryText, query, "And");
    $().SPServices({
        operation: "GetListItems",
        async: false,
        listName: "Tasks",
        CAMLQueryOptions: '<QueryOptions><ViewAttributes Scope="Recursive"/></QueryOptions>',
        CAMLRowLimit: 100,
        CAMLViewFields: "<ViewFields><FieldRef Name='ID' /><FieldRef Name='Title' /><FieldRef Name='Body' /><FieldRef Name='Author' /><FieldRef Name='Created' /><FieldRef Name='Modified' /><FieldRef Name='Status' /><FieldRef Name='WorkflowName' /><FieldRef Name='WorkflowOutcome' /><FieldRef Name='AssignedTo' /></ViewFields>",
        CAMLQuery: "<Query><Where>" + queryText + "</Where></Query>",
        completefunc: function (xData, Status) {
            matchingWorkflowTasksCount = $(xData.responseXML).SPFilterNode("z:row").length;
            $(xData.responseXML).SPFilterNode("z:row").each(function () {
                var workflowTaskId = parseInt($(this).attr('ows_ID'));
                var workflowTitle = $(this).attr('ows_Title');
                var workflowBody = $(this).attr('ows_Body');
                var workflowStatus = $(this).attr('ows_Status');
                var workflowOutcome = $(this).attr('ows_WorkflowOutcome');
                var workflowName = $(this).attr('ows_WorkflowName');
                var workflowTaskCreated = $(this).attr('ows_Created');
                var workflowTaskModified = $(this).attr('ows_Modified');
                var workflowAssignedTo = $(this).attr('ows_AssignedTo').split(";#")[1];
                var workflowRequestedBy = $(this).attr('ows_Author').split(";#")[1];
                var task = new Object();
                task.workflowTaskId = workflowTaskId;
                task.workflowBody = workflowBody;
                task.workflowTitle = workflowTitle;
                task.workflowStatus = workflowStatus;
                task.workflowOutcome = workflowOutcome;
                task.workflowName = workflowName;
                task.workflowTaskCreated = workflowTaskCreated;
                task.workflowTaskModified = workflowTaskModified;
                if (task.workflowOutcome == null) {
                    task.workflowOutcome = "";
                }
                task.workflowAssignedTo = workflowAssignedTo;
                task.workflowRequestedBy = workflowRequestedBy;
                returnedTasks.push(task);
            });
        }
    });
    if (matchingWorkflowTasksCount > 0) {
        buildRelatedWorkflowTasksTable();
    }
}


function buildRelatedWorkflowTasksTable() {
    //It is a form page if the id is not null in the query string
    var listItemInfo = '<div id="relatedTasks"><h2>Workflow Tasks</h2>';
    listItemInfo += "<table class='workflowSection' style='border-collapse:collapse' width='90%'>";
    listItemInfo += "<tr>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>ID</td>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>Title</td>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>Body</td>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>Status</td>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>Outcome</td>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>Assigned To</td>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>Requested By</td>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>Workflow</td>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>Created</td>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>Modified</td>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>Result</td>";
    listItemInfo += "</tr>";

    for (var task in returnedTasks) {
        listItemInfo += "<tr>";
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + returnedTasks[task].workflowTaskId + "</td>";
        var strmodalURL = L_Menu_BaseUrl + "/Lists/Tasks/DispForm.aspx?ID=" + returnedTasks[task].workflowTaskId;
        var strFormatURL = '\n';
        strFormatURL += '<a ';
        strFormatURL += 'href="#';
        strFormatURL += '" ';
        strFormatURL += 'onclick="return !openTasksListItemInModalPopup(\'' + strmodalURL + '\');"';
        strFormatURL += '>';
        strFormatURL += returnedTasks[task].workflowTitle;
        strFormatURL += '</a>';
        strFormatURL += '<br/>';
        listItemInfo += '<td class=\'ms-formbody\'>';
        if (strFormatURL.toString()) {
            listItemInfo += strFormatURL.toString();
        }
        listItemInfo += '</td>';
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + returnedTasks[task].workflowBody + "</td>";
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + returnedTasks[task].workflowStatus + "</td>";
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + returnedTasks[task].workflowOutcome + "</td>";
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + returnedTasks[task].workflowAssignedTo + "</td>";
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + returnedTasks[task].workflowRequestedBy + "</td>";
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + returnedTasks[task].workflowName + "</td>";
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + returnedTasks[task].workflowTaskCreated + "</td>";
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + returnedTasks[task].workflowTaskModified + "</td>";

        resultImageUrl = "";
        if (returnedTasks[task].workflowOutcome == "Approved") {
            resultImageUrl = "<img src='../../SiteAssets/images/approved.png'/>";
        } else if (returnedTasks[task].workflowOutcome == "Rejected") {
            resultImageUrl = "<img src='../../SiteAssets/images/rejected.png'/>";
        } else {
            resultImageUrl = "<img src='../../SiteAssets/images/notstarted.png'/>";
        }
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + resultImageUrl + "</td>";
        listItemInfo += "</tr>";
    }
    listItemInfo += '</table></div>';
    $('.ms-formline').append(listItemInfo);
}

function openTasksListItemInModalPopup(strTaskListURL) {
    var url = strTaskListURL;
    var options = {
        //CHANGE THE URL VALUE                                                                                                                                                         
        url: url,
        width: 700,
        height: 600,
        dialogReturnValueCallback: Function.createDelegate(null, onTaskButtonClosedCallBack)
    };
    SP.UI.ModalDialog.showModalDialog(options);
}

function onTaskButtonClosedCallBack() {
    DoInlineWorkflowTasks();
}


function PopulateWorkflowHistoryItems() {
    var ctx = new SP.ClientContext.get_current();
    list = ctx.get_web().get_lists().getByTitle($(".die").find("a").text());
    ctx.load(list);
    ctx.executeQueryAsync(GetRelatedHistoryItemsForCurrentItem, null);

}
function GetRelatedHistoryItemsForCurrentItem(sender, args) {

    var queryText = "";
    currentlistGuid = list.get_id();
    var caml = new CamlBuilder();
    caml = caml.Where();

    var query = caml.TextField('List').Contains(currentlistGuid).And().IntegerField('Item').EqualTo(currentItemId).ToString().slice(7, -8);
    queryText = joinQueryElements(queryText, query, "And");
    $().SPServices({
        operation: "GetListItems",
        async: false,
        listName: "Workflow History",
        CAMLQueryOptions: '<QueryOptions><ViewAttributes Scope="Recursive"/></QueryOptions>',
        CAMLRowLimit: 100,
        CAMLViewFields: "<ViewFields><FieldRef Name='ID' /><FieldRef Name='Author' /><FieldRef Name='Created' /><FieldRef Name='_ModerationComments' /><FieldRef Name='Modified' /><FieldRef Name='Description' /></ViewFields>",
        CAMLQuery: "<Query><Where>" + queryText + "</Where></Query>",
        completefunc: function (xData, Status) {
            matchingHistoryItemsCount = $(xData.responseXML).SPFilterNode("z:row").length;


            $(xData.responseXML).SPFilterNode("z:row").each(function () {
                var workflowHistoryItemId = parseInt($(this).attr('ows_ID'));
                var workflowHistoryDescription = $(this).attr('ows_Description');
                var workflowApproverComments = $(this).attr('ows__ModerationComments');
                if (workflowApproverComments == null) {
                    workflowApproverComments = "";
                }
                var workflowHistoryCreated = $(this).attr('ows_Created');
                var workflowHistoryModified = $(this).attr('ows_Modified');

                var history = new Object();
                history.workflowHistoryItemId = workflowHistoryItemId;
                history.workflowHistoryDescription = workflowHistoryDescription;
                history.workflowHistoryCreated = workflowHistoryCreated;
                history.workflowHistoryModified = workflowHistoryModified;

                returnedHistoryItems.push(history);
            });
        }
    });
    if (matchingHistoryItemsCount > 0) {
        buildRelatedWorkflowHistoryTable();
    }


}

function buildRelatedWorkflowHistoryTable() {
    //It is a form page if the id is not null in the query string
    var listItemInfo = '<div id="relatedHistory"><h2>Workflow History</h2>';
    listItemInfo += "<table class='workflowHistory' style='border-collapse:collapse' width='90%'>";
    listItemInfo += "<tr>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>ID</td>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>Description</td>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>Created</td>";
    listItemInfo += "<td class='ms-ph' style='font-weight:bold;color:black;'>Modified</td>";
    listItemInfo += "</tr>";

    for (var historyItem in returnedHistoryItems) {
        listItemInfo += "<tr>";
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + returnedHistoryItems[historyItem].workflowHistoryItemId + "</td>";
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + returnedHistoryItems[historyItem].workflowHistoryDescription + "</td>";
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + returnedHistoryItems[historyItem].workflowHistoryCreated + "</td>";
        listItemInfo += "<td class='ms-formbody' style='text-align: left;'>" + returnedHistoryItems[historyItem].workflowHistoryModified + "</td>";
        listItemInfo += "</tr>";
    }


    listItemInfo += '</table></div>';
    $('#relatedTasks').append(listItemInfo);
}










function joinQueryElements(mainQuery, newQuery, operator) {
    if (mainQuery.length > 0) {
        return "<" + operator + ">" + mainQuery + newQuery + "</" + operator + ">";
    } else return newQuery;
}

function GetQueryStringVal(sParam) {
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            // replace the Unicode Wide "&" character with the normal one
            var theValue = sParameterName[1].replace("%C3%AF%C2%BC%C2%86", "&");
            //%20%C3%AF%C2%BC%C2%82 is the unicode wide quote character, in case it is required in the future
            return theValue;
        }
    }
}